package com.gxa.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gxa.stu.entity.pojo.TbManager;
import com.gxa.user.mapper.TbManagerMapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.List;

@Service(interfaceName = "userDetailsService")
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private TbManagerMapper tbManagerMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        LambdaQueryWrapper<TbManager> tbManagerLambdaQueryWrapper = Wrappers.lambdaQuery(TbManager.class);
        tbManagerLambdaQueryWrapper.eq(TbManager::getMgrName,s);
        TbManager tbManager = tbManagerMapper.selectOne(tbManagerLambdaQueryWrapper);
        if(tbManager == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        List<GrantedAuthority> role = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        return new User(tbManager.getMgrNum(),new BCryptPasswordEncoder().encode(tbManager.getMgrPwd()),role);
    }
}
